/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hybris;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Arrays;
import java.util.Random;
/**
 *
 * @author menderleit
 */
public class Starfield {

    private int numStars;
    private double width;
    private double height;
    private double depth;
    private double speed;
    private int alpha;
    private Vector3[] v;
    private Random rnd;

    public Starfield(int numStars, double width, double height, double depth) {
        rnd = new Random();
        this.numStars = numStars;
        v = new Vector3[numStars];
        this.width = width;
        this.height = height;
        this.depth = depth;
        speed = 0.5;
        alpha = 0;
        for (int i = 0; i < numStars; i++) {
            v[i] = new Vector3(rnd.nextDouble() * width - (width / 2.0), rnd.nextDouble() * height - (height / 2.0), rnd.nextDouble() * depth);
        }
    }

    public void update(long difTime) {
        for (int i = 0; i < numStars; i++) {
            v[i].setZ(v[i].getZ() - speed * difTime);
            if (v[i].getZ() <= 0.0) {
                v[i].setZ(v[i].getZ() + depth);
            }
        }
    }

    public void draw(Graphics g, int SW, int SH) {
        double POV = (double)((double)SW / (double)SH);
        Arrays.sort(v);
        for (int i = 0; i < numStars; i++) {
            Vector3 t = new Vector3(v[i].getX(), v[i].getY(), v[i].getZ()-25.0);
            v[i].project(POV);
            v[i].map(SW, SH);
            t.project(POV);
            t.map(SW, SH);
            if (v[i].getSX() >= 0 && v[i].getSX() < SW && v[i].getSY() >= 0 && v[i].getSY() < SH && v[i].getZ() > 25.0) {
                int col = 255 - scaleColor(v[i].getZ(), 0.0f, depth);
                int red = clampColor(col-64);
                int green = clampColor(col-48);
                int blue = clampColor(col);
                g.setColor(new Color(red, green, blue, alpha));
                g.drawLine(v[i].getSX(), v[i].getSY(), t.getSX(), t.getSY());
            }
        }
    }
    
    private int clampColor(int color) {
        int newColor = color;
        if(color < 0) {
            newColor = 0;
        }
        if(color > 255) {
            newColor = 255;
        }
        return newColor;
    }
    
    private int scaleColor(double in, double oldMin, double oldMax) {
        return (int)((in / ((oldMax - oldMin) / (255.0 - 0.0))) + 0.0);
    }
    
    public void setAlpha(int alpha) {
        this.alpha = clampColor(alpha);
    }
    
    public void setSpeed(double speed) {
        this.speed = speed;
    }
}
